#include "axiscanvas.h"
#include <math.h>
#include <QApplication>

AxisCanvas::AxisCanvas(QWidget* parent)
    : QWidget(parent)
{
    _tmwidget = new AsixTickMarkWidget;
    _view.setParent(this);
    _view.setScene(&_scene);
    _tmwidget->setParent(this);
    QPointF p = _scene.pixelToScreenCoords(0, 0);
    _view.centerOn(p);
}

void AxisCanvas::resizeEvent(QResizeEvent *event)
{
    QRectF viewrect = _view.sceneRect();
    _tmwidget->setFixedSize(width(), height());
    _view.setFixedSize(width(), height());
    _view.setSceneRect(viewrect.x(), viewrect.y(), width(), height());
    _scene.setSize(width(), height());
}

void AxisCanvas::mousePressEvent(QMouseEvent *event)
{
    QWidget::mousePressEvent(event);
}

void AxisCanvas::mouseReleaseEvent(QMouseEvent *event)
{
    QWidget::mouseReleaseEvent(event);
}

void AxisCanvas::mouseMoveEvent(QMouseEvent *event)
{
    QWidget::mouseMoveEvent(event);
}

void AxisCanvas::wheelEvent(QWheelEvent *event)
{
    if ( _ctrlpress )
    {
        // 滚轮的滚动量
        QPoint scrollAmount = event->angleDelta();
        // 正值表示滚轮远离使用者（放大），负值表示朝向使用者（缩小）
        scrollAmount.y() > 0 ? zoomIn() : zoomOut();
    }
}

void AxisCanvas::keyPressEvent(QKeyEvent *event)
{
    if ( Qt::Key_Control == event->key() )
    {
        _ctrlpress = true;
    }
}

void AxisCanvas::keyReleaseEvent(QKeyEvent *event)
{
    if ( Qt::Key_Control == event->key() )
    {
        _ctrlpress = false;
    }
}

AxisSprite *AxisCanvas::createMapObject(int w, int h)
{
    AxisSprite* m = new AxisSprite;
    m->setSize(w, h, _scene.getMap()->getGridWidth(), _scene.getMap()->getGridHeight());
    return m;
}

void AxisCanvas::addMapObject(AxisSprite *m, int gridx, int gridy)
{
    QPointF scpos = _scene.tileToScreenCoords(gridx, gridy);
    _scene.addSprite(m);
    m->updatePos(gridx, gridy);
}

void AxisCanvas::zoomIn()
{
    zoom(1 + 0.01);
}

void AxisCanvas::zoomOut()
{
    zoom(1 - 0.01);
}

void AxisCanvas::zoom(qreal scalefactor)
{
    _view.scale(scalefactor, scalefactor);
    _scale *= scalefactor;
}
